package com.lishem.top100._07linkedlist;


import com.lishem.common.ListNode;

/**
 * https://leetcode.cn/problems/sort-list/description/
 * <p>
 * 给你链表的头结点 head ，请将其按 升序 排列并返回 排序后的链表 。
 * <p>
 * 示例 1：
 * <p>
 * 输入：head = [4,2,1,3]
 * <p>
 * 输出：[1,2,3,4]
 * <p>
 * 示例 2：
 * <p>
 * 输入：head = [-1,5,3,4,0]
 * <p>
 * 输出：[-1,0,3,4,5]
 * <p>
 * 示例 3：
 * <p>
 * 输入：head = []
 * <p>
 * 输出：[]
 */
public class _12LetCode148_排序链表 {

    // 链表归并
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode fast = head.next;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode tmp = slow.next;
        slow.next = null;
        ListNode left = sortList(head);
        ListNode right = sortList(tmp);
        ListNode newHead = new ListNode(0);
        ListNode cur = newHead;
        while (left != null && right != null) {
            if (left.val < right.val) {
                cur.next = left;
                left = left.next;
            } else {
                cur.next = right;
                right = right.next;
            }
            cur = cur.next;
        }
        cur.next = left == null ? right : left;
        return newHead.next;
    }

    public static void main(String[] args) {
        _12LetCode148_排序链表 sol = new _12LetCode148_排序链表();
        ListNode head = new ListNode(4);
        head.next = new ListNode(2);
        head.next.next = new ListNode(1);
        head.next.next.next = new ListNode(3);
        ListNode.printListNode(sol.sortList(head));
    }
}
